import java.util.HashMap;
import java.util.Map;

public class Solution560 {
    public int subarraySum(int[] nums, int k) {
        Map<Integer,Integer> preSum = new HashMap<>();
        preSum.put(0,1);
        int res = 0,sum0_i = 0;
        for (int i = 0; i < nums.length; i++) {
            sum0_i += nums[i];
            int sum0_j = sum0_i - k;
            if(preSum.containsKey(sum0_j)){
                res += preSum.get(sum0_j);
            }
            preSum.put(sum0_i,preSum.getOrDefault(sum0_i,0)+1);
        }
        return res;
    }
}
